const path = require('path')

const Common = require('../common/common.js')

const uniPay = require(path.resolve(__dirname, '../../unipay/index.js'))

// 支付对象
class Pay {
  // provider取值 wx/alipay
  constructor (options = {}) {
    this.provider = options.provider ? options.provider : 'wx'
    const configData = Common.config.pay[this.provider]
    if (configData) {
      let payConfig = { ...configData }
      const appId = Common.config.pay.appId[options.appType]
      payConfig.appId = appId
      this.options = {
        ...options,
        ...payConfig
      }
      this.init(payConfig)
    }
  }
  
  // 初始化支付对象
  init (data) {
    switch (this.provider) {
      case 'wx':
        this.payInstance = uniPay.initWeixin(data)
        break
      default:
        this.payInstance = null
    }
  }
  
  // 常规下单，获取支付参数
  async getOrder (order) {
    if (!this.payInstance) {
      return Common.error('PAY_INIT_FAILED')
    }
    
    try {
      const data = {
        openid: this.options.openid,
        body: order.description,
        outTradeNo: order._id,
        totalFee: order.price,
        tradeType: this.options.tradeType,
        // 支付结果通知地址
        notifyUrl: this.getNotifyUrl()
      }
      Common.log.log(data, '支付参数')
      const orderRes = await this.payInstance.getOrderInfo(data)
      return orderRes
    }
    catch (e) {
      return Common.error('PAY_FAILED', e)
    }
  }
  
  // 处理支付结果通知
  async verifyNotify (event) {
    if (!this.payInstance) {
      return Common.error('PAY_INIT_FAILED')
    }
    
    return await this.payInstance.verifyPaymentNotify(event)
  }
  
  // 获取支付通知地址
  getNotifyUrl () {
    return Common.config.pay.notifyUrl + '/' + this.options.provider 
      + '_' + this.options.appType
  }
}

module.exports = Pay
